﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITesting;
using System.IO;
using Microsoft.VisualStudio.WebHost;

namespace UIDefinitionTutorial
{
    [CodedUITest]
    [DeploymentItem(@"SampleSite/Sample.html")]
    public class SamplePageTests
    {
        private static Server m_webServer;
        public TestContext TestContext { get; set; }        

        [ClassInitialize]
        public static void StartWebServer(TestContext testContext)
        {
            m_webServer = new Server(15001, "/", testContext.DeploymentDirectory);
            m_webServer.Start();            
        }

        [ClassCleanup]
        public static void StopWebServer()
        {
            if (m_webServer != null)
            {
                m_webServer.Stop();
                m_webServer = null;
            }
        }

        private SampleDefinition.UISamplePage CreateSamplePage()
        {
            return new SampleDefinition.UISamplePage(new Uri("http://localhost:15001/Sample.html")) { CloseOnPlaybackCleanup = true };
        }

        [TestMethod]        
        public void SetAndVerifyTextBox()
        {
            const string anonymousText = "Sample Text";

            using (var page = CreateSamplePage())
            {
                var textBox = page.Content.TextBox;
                textBox.Text = anonymousText;

                Assert.IsTrue(textBox.Exists);
                Assert.AreEqual(anonymousText, textBox.Text);
            }
        }

        [TestMethod]
        public void VerifyHeaderText()
        {
            using (var page = CreateSamplePage())
            {
                Assert.AreEqual("Header Content", page.Header.Text.InnerText);
            }
        }

        [TestMethod]
        public void ClickInsertButton()
        {
            using (var page = CreateSamplePage())
            {                
                Mouse.Click(page.Content.Insert);
            }
        }

        [TestMethod]
        public void CountListItems()
        {
            using (var page = CreateSamplePage())
            {
                var items = page.Content.List.Items;

                Assert.AreEqual(3, items.Length);
                Assert.AreEqual("One", items[0].InnerText.Trim());
                Assert.AreEqual("Two", items[1].InnerText.Trim());
                Assert.AreEqual("Three", items[2].InnerText.Trim());
            }
        }
    }
}
